﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using University.Workshop.Presenters.Views;
using University.Workshop.Business;
using University.Workshop.Model;
using System.Collections.ObjectModel;
using System.Data.SqlClient;
using University.Workshop.DataAccess;

namespace University.Workshop.Presenters
{
	public class SendTicketPresenter
	{
		public ISendTicketView View { get; set; }

		public SendTicketPresenter(ISendTicketView view)
		{
			this.View = view;
		}

		public void ChangePurchasesPage(int pageNumber, string userEmail)
		{
			Collection<PurchasedProduct> purchases = TicketManager.GetPurchasesWithoutTicketByUser(userEmail);
			Collection<PurchasedProduct> purchasesPage = new Collection<PurchasedProduct>();

			int min = 0, max = 0;
			checked
			{
				min = (pageNumber - 1)*5;
				max = (pageNumber*5) - 1;
			}
			for (int i = 0; i <= max && i < purchases.Count; i++)
			{
				if (i >= min && i <= max)
					purchasesPage.Add(purchases[i]);
			}

			this.View.SetActualPurchasesPage(purchasesPage, purchases.Count);
		}

		public void SubmitTicketInformation()
		{
			try
			{
				if (string.IsNullOrEmpty(this.View.IssueTitle) || string.IsNullOrEmpty(this.View.Description))
				{
					throw new ValidationException("All (*) fields are required.");
				}
				Ticket ticket = TicketManager.SendTicket(View.IssueTitle, View.Description, View.OrderId, View.Priority);
				if (ticket != null)
				{
					this.View.Result = "Ticket sent succesfully!";
				}
			}

			catch (ValidationException vex)
			{
				View.Result = vex.Message;
			}

			catch (BusinessException bex)
			{
				View.Result = bex.Message;
			}

			catch (SqlException)
			{
				View.Result = "An unkown method ocurred!";
			}
		}

		public void ChangeProductName(long orderId)
		{
			this.View.PurchasedProductName = (OrderDataAccess.ProductByIdOfOrder(orderId)).Name;
		}
	}
}
